﻿using UnityEngine;
using System.Collections;
using ProtoBuf.Message;
using Dict.Blo;

namespace UI
{
    public class UICopyRunMapHeroInfo : MonoBehaviour
    {
        public UITexture heroIcon;
        public UILabel heroName;
        public UILabel heroHp;
        public UISprite heroHpBar;
        public UISprite[] heroAngleBars;

        string texResUrl = "";

        IEnumerator LoadTexture()
        {
            AssetLoad.AssetBundleManager.Instance.LoadAssetBundle(texResUrl);
            while (!AssetLoad.AssetBundleManager.Instance.IsLoadedAssetBundle(texResUrl))
            {
                yield return 1;
            }
            heroIcon.mainTexture = AssetLoad.AssetBundleManager.Instance.GetAssetFromBundle(texResUrl, CommonMethod.GetAssetNameFromAssetBundleName(texResUrl), typeof(Texture2D)) as Texture2D;
        }

        void UnloadTexture()
        {
            heroIcon.mainTexture = null;
            AssetLoad.AssetBundleManager.Instance.UnloadAssetBundle(texResUrl);
        }

        void OnDisable()
        {
            StopAllCoroutines();
            UnloadTexture();
        }

        public void Init(object o)
        {
            var info = (SCCopyRunMapInfo)o;

            //var uid = StaticData.playerData.heroWarUID;
            var leaderHero = StaticData.playerData.InstPlayerData.GetBattleCamp(1).hero;
            var path = "HeroHeader/" + leaderHero.heroData.iconName;

            texResUrl = path;
            StartCoroutine(LoadTexture());

            var curHp = 0.0;
            var totalHp = 0.0;
            heroName.text = info.battlePlayer.nickName;
            var formation = info.battlePlayer.formation;
            foreach(var f in formation)
            {
                curHp += f.inst.curHp;
                totalHp += f.prop.hp;
            }

            var inHp = (int)curHp;
            var inMaxHp = (int)totalHp;

            heroHp.text = inHp + "/" + "" + inMaxHp;
            heroHpBar.fillAmount = (float)curHp / (float)totalHp;

            float maxAngle = (float)DictConfigBlo.GetMaxAnger();
            float curAngle = 0f;
            if (info.battlePlayer.inst!=null)
            {
                curAngle = (float)info.battlePlayer.inst.anger;
            }
            float value = curAngle * 3f/ maxAngle;
            
            for (int i=0; i<3;i++)
            {
                heroAngleBars[i].fillAmount = Mathf.Clamp01(value);
                value = value - 1f;
            }
        }
    }
}